<template>
  <div class="contract-expense-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>合同费用明细</span>
        </div>
      </template>
      
      <!-- 查询条件 -->
      <el-form :model="queryForm" label-width="100px" class="query-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数据库连接">
              <el-select 
                v-model="queryForm.databaseId" 
                placeholder="请选择数据库" 
                style="width: 100%" 
                @change="handleDatabaseChange"
              >
                <el-option
                  v-for="item in databaseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关键词">
              <el-input
                v-model="queryForm.keyword"
                placeholder="请输入供应商编号或名称"
                clearable
                @keyup.enter="handleQuery"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="text-align: right;">
            <el-button type="primary" @click="handleQuery" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button 
              type="success" 
              @click="handleExport" 
              :disabled="tableData.length === 0"
              plain
            >
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          v-loading="loading"
          :height="tableHeight"
          stripe
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="supplierCode" label="供应商编号" width="120" />
          <el-table-column prop="supplierName" label="供应商名称" width="200" show-overflow-tooltip />
          <el-table-column prop="contractNo" label="合同号" width="150" />
          <el-table-column prop="chargeName" label="费用名" width="150" />
          <el-table-column prop="chargeValue" label="费用值" width="120" align="right">
            <template #default="scope">
              ￥{{ scope.row.chargeValue.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="chargeDate" label="扣款日期" width="180" />
          <el-table-column prop="settlementCycle" label="结算周期" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getSettlementType(scope.row.settlementCycle)">
                {{ scope.row.settlementCycle }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 汇总行 -->
        <div class="summary-bar">
          <div class="summary-item">
            <span class="summary-label">查询结果：</span>
            <span class="summary-value">共 <strong>{{ totalCount }}</strong> 条费用明细</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">费用总额：</span>
            <span class="summary-value total-amount">￥{{ totalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { getDatabaseList } from '@/api/database'
import { API_BASE_URL } from '@/config/api'
import * as XLSX from 'xlsx'

interface DatabaseItem {
  id: number
  name: string
}

interface QueryForm {
  databaseId: number | null
  keyword: string
}

interface ContractExpenseItem {
  supplierCode: string
  supplierName: string
  contractNo: string
  chargeName: string
  chargeValue: number
  chargeDate: string
  settlementCycle: string
}

const loading = ref(false)
const tableHeight = ref(500)
const databaseList = ref<DatabaseItem[]>([])
const tableData = ref<ContractExpenseItem[]>([])

const queryForm = reactive<QueryForm>({
  databaseId: null,
  keyword: ''
})

const totalCount = computed(() => tableData.value.length)
const totalAmount = computed(() => 
  tableData.value.reduce((sum, item) => sum + item.chargeValue, 0)
)

// 加载数据库列表
const loadDatabaseList = async () => {
  try {
    const res = await getDatabaseList()
    if (res.success && res.data) {
      databaseList.value = res.data
      if (databaseList.value.length > 0) {
        queryForm.databaseId = databaseList.value[0].id
      }
    }
  } catch (error) {
    console.error('加载数据库列表失败:', error)
    ElMessage.error('加载数据库列表失败')
    databaseList.value = []
  }
}

// 数据库切换
const handleDatabaseChange = (value: number) => {
  console.log('切换数据库:', value)
  tableData.value = []
}

// 查询
const handleQuery = async () => {
  if (!queryForm.databaseId) {
    ElMessage.warning('请选择数据库连接')
    return
  }

  loading.value = true
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/report/contract-expense`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        databaseId: queryForm.databaseId,
        keyword: queryForm.keyword
      })
    })

    const result = await response.json()
    
    if (result.success) {
      tableData.value = result.data || []
      ElMessage.success(`查询成功，共 ${tableData.value.length} 条数据`)
    } else {
      ElMessage.error(result.message || '查询失败')
      tableData.value = []
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请检查网络连接')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 重置
const handleReset = () => {
  queryForm.keyword = ''
  tableData.value = []
}

// 获取结算周期标签类型
const getSettlementType = (cycle: string) => {
  const typeMap: Record<string, string> = {
    '一次': 'success',
    '每月': 'primary',
    '每年': 'warning',
    '周期': 'info',
    '未知': 'danger'
  }
  return typeMap[cycle] || 'info'
}

// 导出Excel
const handleExport = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  try {
    const exportData = tableData.value.map((item, index) => ({
      '序号': index + 1,
      '供应商编号': item.supplierCode,
      '供应商名称': item.supplierName,
      '合同号': item.contractNo,
      '费用名': item.chargeName,
      '费用值': '￥' + item.chargeValue.toFixed(2),
      '扣款日期': item.chargeDate,
      '结算周期': item.settlementCycle
    }))

    const worksheet = XLSX.utils.json_to_sheet(exportData)

    const colWidths = [
      { wch: 6 },   // 序号
      { wch: 15 },  // 供应商编号
      { wch: 25 },  // 供应商名称
      { wch: 18 },  // 合同号
      { wch: 15 },  // 费用名
      { wch: 15 },  // 费用值
      { wch: 20 },  // 扣款日期
      { wch: 12 }   // 结算周期
    ]
    worksheet['!cols'] = colWidths

    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '合同费用明细')

    const now = new Date()
    const fileName = `合同费用明细_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}.xlsx`

    XLSX.writeFile(workbook, fileName)

    ElMessage.success(`成功导出 ${tableData.value.length} 条费用数据`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

onMounted(() => {
  loadDatabaseList()
  tableHeight.value = window.innerHeight - 300
})
</script>

<style scoped>
.contract-expense-container {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.query-form {
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.summary-bar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 40px;
  padding: 16px 20px;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-top: none;
  font-size: 14px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-label {
  color: #606266;
}

.summary-value {
  color: #303133;
  font-weight: 500;
}

.summary-value strong {
  color: #409eff;
  font-size: 16px;
}

.total-amount {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 600;
}
</style>

